package com.fenyin.samples.study.quartz;  

import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;

/**
 * 
 *@Title:  
 *@Description:  编程式调度器
 *@Author:fengzhichao  
 *@Since:2012-9-7  
 *@Version:1.1.0
 */
public class PublishScheduler {
	
	private static final Log logger = LogFactory.getLog(PublishScheduler.class);
	
	private Scheduler scheduler;
	
	private final ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(10);
	
	public PublishScheduler(){
		try {
			this.scheduler = StdSchedulerFactory.getDefaultScheduler();
		} catch (SchedulerException e) {
			logger.error("ProgramScheduler create error",e);
		}
	}
	
	public void scheduleJob() throws SchedulerException, ParseException{
		//create and init JobDetail instance
		JobDetail jobDetail = new JobDetail("scan_directory_job_first", Scheduler.DEFAULT_GROUP,PublishSchedulerListener.class);
		
		CronTrigger trigger= new CronTrigger("scan_directory_trigger_first",Scheduler.DEFAULT_GROUP,"0 14 23 * * ?");
		trigger.setStartTime(new Date());
		
		scheduler.scheduleJob(jobDetail, trigger);
	}
	
	public void rescheduleJob(int secend,int min,int hour,int count,long timeperiod) throws SchedulerException, ParseException{
		String triggerName = "scan_directory_trigger";
		Date runDate = TriggerUtils.getDateOf(secend,min,hour);
		SimpleTrigger trigger = (SimpleTrigger) scheduler.getTrigger(triggerName, Scheduler.DEFAULT_GROUP);
		trigger.setStartTime(runDate);
		trigger.setRepeatCount(count);
		trigger.setRepeatInterval(timeperiod);
		scheduler.rescheduleJob(triggerName, Scheduler.DEFAULT_GROUP, trigger);
	}
	
	
	public void scheduleStart() throws SchedulerException{
		logger.info("ProgramScheduler is staring....");
		scheduler.start();
	}
	
	public static void main(String[] args){
		PublishScheduler scheduler = null;
		try {
			scheduler = new PublishScheduler();
			scheduler.scheduleJob();
			
			scheduler.scheduleStart();
			Thread.sleep(120000);
//			System.out.println("first reschedule....");
//			scheduler.rescheduleJob(0,59,18,20,1000);
//			Thread.sleep(600000);
			
		} catch (SchedulerException e) {
			logger.error("ProgramScheduler scheduleJob error",e);
		} catch (ParseException e) {
			logger.error("ProgramScheduler crontrigger parse error",e);
		} catch (InterruptedException e) {
			logger.error("Thread error",e);
		}
	}
}
